#!/bin/bash
source $DRAW_INI
source $DRAW_CFG

samtools view -bq 1 s_${1}.indel_realign.bam -o s_${1}_uniq.bam

EXITSTATUS=$?

java -Xmx2g -jar $GENOMICS_JAR/MarkDuplicates.jar \
VALIDATION_STRINGENCY=SILENT \
INPUT=s_${1}_uniq.bam \
OUTPUT=s_${1}_nodup_uniq.bam \
REMOVE_DUPLICATES=true \
CREATE_INDEX=true \
METRICS_FILE=metrics \
OPTICAL_DUPLICATE_PIXEL_DISTANCE=10

EXITSTATUS=$?

if [ $EXITSTATUS -ne 0 ];then exit $EXITSTATUS;fi



if [ -s s_${1}_nodup_uniq.bam ]
then
 samtools index s_${1}_nodup_uniq.bam
else
 exit 100
fi


# Check for core dumps (errors) from Picard
CORE_LIST=$(ls core.*)
if [ -n "$CORE_LIST" ]
  then
   echo "Found core dumps. Exiting with error."
   exit 100
fi

# Check BAM EOF
BAM_28=$(tail -c 28 s_${1}_nodup_uniq.bam|xxd -p)
if [ "$MAGIC28" != "$BAM_28" ]
then
  echo "Error with BAM EOF" 1>&2
  exit 100
fi

exit $EXITSTATUS
